const mssql = require("mssql");
import config from "../../src/config";
import { ReturnMessage } from "../type";
import { CapOptions } from "../type";
import logger from "@utils/log";
import { paramsType } from "../type";
//將數據庫操作封裝成類
class DBConnect {
  private pool: any;
  private poolConnect: any;

  async init(): Promise<void> {
    try {
      this.pool = new mssql.ConnectionPool(config);
      this.poolConnect = this.pool.connect();
    } catch (err: any) {
      logger.error(err.message);
    }
  }
  async doRelease(): Promise<void> {
    try {
      if (this.pool) {
        await this.pool.close(); //释放连接，将连接放回池中
      }
    } catch (err: any) {
      logger.error(err.message);
    }
  }
  //連帶查詢一併返回
  execute(options: CapOptions): Promise<ReturnMessage> {
    const { sql, params } = options; //解構操作數據庫的參數，目前只解構sql
    return new Promise(async (resolve, reject) => {
      try {
        //等待初始化
        await this.init();
        await this.poolConnect;
        const request = new mssql.Request(this.pool);
        try {
          //綁定參數，防止SQL注入
          if (params?.length) {
            params.forEach((param: paramsType) => {
              request.input(param.name, param.value);
            });
          }
          //執行SQL
          logger.info("執行sql語句:" + sql);
          const result: any = await request.query(sql);
          await this.doRelease();
          resolve({
            code: 200,
            message: "成功",
            data: result.recordset,
          });
        } catch (err: any) {
          logger.error("執行SQL錯誤" + err.originalError.info.message);
          reject("后台异常！请联系开发者处理！");
        }
      } catch (err) {
        logger.error("打開連接錯誤" + err);
        reject("打開連接池失敗");
      }
    });
  }
}

export default new DBConnect();
